import datetime

from flask_jwt_extended import (
    jwt_required,
    get_jwt_identity,
)   

from flask_restx import (
    Namespace, 
    Resource,
    fields
)
from flask import (
    abort,
    request,
    jsonify,
)
from sqlalchemy import (
    select,
    update,
    func,
)
from app.apis.serializer import ShortTime, TimeAgo
from app.models import (
    User,
    Friendships,
    FriendMessage,
    FriendRequest
)
from app import db, redis_client
ns = Namespace('friends', description='好友相关操作')

friend_request_model = ns.model(
    'friend request model',
    {
        'id' : fields.Integer(attribute = 'request.id'), # 申请表所在id行
        'sender' : fields.String(attribute = 'request.sender_name'),
        'receiver' : fields.String(attribute = 'request.receiver_name'),
        'status' : fields.Integer(attribute = 'request.status'),
        'time' : TimeAgo()
    }
)

friendship_model = ns.model(
    'friend model',
    {
        'id': fields.Integer(attribute='friend_id'),
        'nickname': fields.String(attribute='friend.nickname'),
        'avatar': fields.String('friend.avatar'),
        'last_active_time': TimeAgo(),
        'unread_count':fields.Integer(),
        'is_online': fields.Boolean(attribue='friend.is_online'),    
    }
)

friend_message_model = ns.model(
    'friend message model',
    {
        'id': fields.Integer(),
        'type': fields.String(),
        'content': fields.String(),
        'sender_id': fields.Integer(),
        'sender_name': fields.String(),
        'sender_nickname': fields.String(),
        'sender_avatar': fields.String(),
        'receiver_id': fields.Integer(),
        'created_at': fields.String(),
        'send_time': ShortTime(attribute='created_at'),
        'is_recalled': fields.Boolean(),
    }
)

def send_friend_message(message):
    ### 发送好友消息 ###
    # 发送给自己
    return

def send_friend_recalled_message(message):
    return

def send_friend_unread_update_event(message):
    return

@ns.route('')
class FriendList(Resource):
    @jwt_required()
    @ns.marshal_with(friendship_model)
    def get(self):
        user_id = int(get_jwt_identity())

        # 获取好友列表
        friends = db.session.scalars(
            select(Friendships).
            where(
                Friendships.user_id == user_id,
                # 查找未主动删除的好友
                Friendships.is_delete == False,
            )
        ).all()

        return friends
    
    @jwt_required()
    @ns.marshal_with()
    def post(self):
        # 申请添加好友
        user_id = int(get_jwt_identity())

        user_name = request.json.get('user_name')
        friend_name = request.json.get('friend_name')


        friend = db.session.scalars(
            select(User).where(
                User.user_name == friend_name,
            )
        ).first()

        if not friend:
            abort(400, message='用户不存在')

        # 检查是否已添加
        friendship = db.session.scalars(
            select(Friendships).
            where(
                Friendships.user_id == user_id,
                Friendships.friend_id == friend.id,
                Friendships.is_delete == False,
            )
        ).first()

        if friendship:
            abort(400, message='你已添加对方为好友')


        # 添加好友申请
        request = FriendRequest(
            send_name = user_name,
            receive_name = friend.user_name,
            statue = 0
        )

        try:
            db.session.add(request)
            db.session.commit()
            res = '好友申请发送成功'
        except:
            db.session.rollback()
            res = '好友申请发送失败'
        
        return jsonify(
            {
                'res' : res
            }
        )
@ns.route('/requests')
class FriendRequestsList(Resource):
    @jwt_required()
    @ns.marshal_with(friend_request_model)
    def get(self):
        ### 查看所有好友申请 ### 
        user_id = int(get_jwt_identity())

        requests = db.session.scalars(
            select(FriendRequest).
            where(FriendRequest.receiver_id == user_id)
        ).all()

        return requests

    @jwt_required()
    def post(self):
        ### 好友申请回复 ### 
        user_id = int(get_jwt_identity())
    
        receiver = request.json.get('receiver')
        sender = request.json.get('sender')
        answer = request.json.get('answer')

        request = db.session.scalars(
            select(FriendRequest).
                where(
                    FriendRequest.receiver_name == receiver,
                    FriendRequest.sender_name == sender
                )
        ).first()

        if not request:
            abort(400, '好友申请不存在')

        #（1）用户拒绝邀请
        if answer == False:
            request.status = '2'
            # 更新状态
            db.session.commit() # ？ 实时更新
        else:
            request.status = '1'
            
            # 添加好友关系

            friend = db.session.scalars(
                select(User)
                .where(User.user_name == sender)
            ).first()

            if not friend:
                abort(400, '申请好友已注销')

            Friendship1 = Friendships(
                user_id = user_id,
                friend_id = friend.id
            )

            Friendship2 = Friendships(
                user_id = friend.id,
                friend_id = user_id
            )

            try:
                db.session.add(Friendship1)
                db.flash()
                db.session.add(Friendship2)
                db.session.commit()
            except:
                db.session.rollback()
                abort(500, '添加好友失败')
            
            # 向 user and friend 发送消息

        return jsonify({
            'status': '操作成功'
        })
        
          




        




@ns.route('/<int:friend_id>/messages')
class FriendMessagesList(Resource):
    @jwt_required()
    @ns.marshal_with(friend_message_model)
    def get(self, friend_id):
        # 获取与好友的聊天列表
        user_id = int(get_jwt_identity())

        # 最后一条已加载消息的时间
        before_time = request.args.get('before_time')

        # 加载条数，默认30
        limit = 30

        # 构建加载条件
        query = (
            select(FriendMessage)
            .where(FriendMessage.is_recalled.is_(False))
            .where(
                (FriendMessage.sender_id == user_id) 
                & (FriendMessage.receiver_id == friend_id)
                | (FriendMessage.sender_id == friend_id)
                & (FriendMessage.receiver_id == user_id)
            )
            .order_by(FriendMessage.created_at.desc())
            .limit(30)
        )

        if before_time:
            before_time = datetime.strptime(before_time, '%Y-%m-%d %H:%M:%S')
            query = query.where(FriendMessage.created_at < before_time)
        
        # 没有before_time，则代表首次加载
        messages = db.session.scalars(query).all()

        return messages

    @jwt_required()
    def post(self, friend_id):
        # 向friend_id发送消息   
        
        friendship = 
